import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, message} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATETIME_FORMAT, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions, getUrl} from './utils';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import styles from './style.css';
import PartSaleOrderSelectPanel from './PartSaleOrderSelectPanel';
import BankSelectPanel from './BankSelectPanel';
import SearchInput from 'Shared/components/SearchInput';
import TextInput from 'Shared/components/TextInput';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
import {getDetail, getPartPrice, getPartSaleOrderById} from './api';
import {transportType, paymentType, partOrderPriceTerms, currency} from '../Enum';
import InputAmount from '../common/InputAmount';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';

const {Description} = DescriptionList;
const FormItem = Form.Item;
class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        partSaleOrder: {},
        details: [],
        showPartSaleOrderSelectPanel: false,
        showBankSelectPanel: false,
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details.map(d => Object.assign({}, d, {
                                order: res.data.details.findIndex(x => x.partId === d.partId) + 1,
                            })),
                            partSaleOrder: res.data.partSaleOrder
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
        const partSaleOrder = getUrl(this.props.history.location.search);
        if(partSaleOrder && partSaleOrder.partSaleOrderId)
            getPartSaleOrderById(partSaleOrder.partSaleOrderId)
                .then(res => {
                    if(res.ok) {
                        const row = res.data;
                        const tmp = row.details.map(d => Object.assign({}, d, {
                            order: row.details.findIndex(x => x.partId === d.partId) + 1,
                            newPartId: d.oldPartId,
                            newPartCode: d.oldPartCode,
                            newPartName: d.oldPartName,
                        }));
                        this.setState({
                            details: tmp,
                            partSaleOrder: row,
                            data: Object.assign({}, this.state.data, {
                                payableAccount: row.account,
                                carier: row.carier,
                                bankId: row.dealerBanks.length === 1 ? row.dealerBanks[0].id : null,
                                bankAccount: row.dealerBanks.length === 1 ? row.dealerBanks[0].account : null,
                            }),
                            hasOperat: true
                        });
                    }
                });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSelectPartSaleOrder = records => {
        getPartSaleOrderById(records.id)
            .then(res => {
                if(res.ok) {
                    const saleOrder = res.data;
                    const tmp = saleOrder.details.map(d => Object.assign({}, d, {
                        order: saleOrder.details.findIndex(x => x.partId === d.partId) + 1,
                        newPartId: d.oldPartId,
                        newPartCode: d.oldPartCode,
                        newPartName: d.oldPartName,
                    }));
                    this.setState({
                        details: tmp,
                        data: Object.assign({}, this.state.data, {
                            payableAccount: saleOrder.account,
                            carier: saleOrder.carier,
                            bankId: saleOrder.dealerBanks.length === 1 ? saleOrder.dealerBanks[0].id : null,
                            bankAccount: saleOrder.dealerBanks.length === 1 ? saleOrder.dealerBanks[0].account : null,
                        }),
                        partSaleOrder: res.data,
                        hasOperat: true,
                        showPartSaleOrderSelectPanel: false
                    });
                }
            });
    }
    onSelectAddedBank = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                bankId: records.id,
                bankAccount: records.account,
            }),
            hasOperat: true,
            showBankSelectPanel: false
        });
    }
    onClickSearchBtn = () => {
        this.setState({showPartSaleOrderSelectPanel: true});
    }
    onClosePartSaleOrderSelectPanel = () => {
        this.setState({showPartSaleOrderSelectPanel: false});
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onClickBankSearchBtn = () => {
        if(!this.state.partSaleOrder.id)
            return message.warn(this.props.intl.formatMessage({
                id: 'NewPanel.message.chooseSaleOrder',
                defaultMessage: '请先选择备件订单'
            }));
        this.setState({showBankSelectPanel: true});
    }
    onCloseBankSelectPanel = () => {
        this.setState({showBankSelectPanel: false});
    }
    onSubmit = () => {
        const {data, partSaleOrder} = this.state;
        const isValid = newOrUpdateOrderValidator(data, partSaleOrder);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, partSaleOrder).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onRefreshPrice = e => {
        const partId = e.target.dataset.id;
        const {partSaleOrder, details} = this.state;
        const condition = {
            partId,
            brandId: partSaleOrder.brandId,
            dealerId: partSaleOrder.dealerId
        };
        this.setState({loading: true});
        getPartPrice(condition)
            .then(res => {
                if(res.ok) {
                    const tmp = details.map(d => {
                        if(d.partId === partId)
                            return Object.assign({}, d, {
                                price: res.data.price,
                                amount: res.data.price * d.quantity
                            });
                        return d;
                    });
                    this.setState({
                        details: tmp,
                        loading: false,
                    });
                } else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    setRowClassName(record) {
        if(record.price && record.isEstimated)
            return styles.rowStyle;
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading, partSaleOrder} = this.state;
        const validateOrderCode = !partSaleOrder.id && this.state.validate ? 'error' : null;
        const validateBankAccount = !data.bankAccount && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.add, this.props.permissions);
        let totalAmount = 0;
        let totalQuantity = 0;
        if(details)
            details.forEach(d => {
                totalAmount += (d.amount);
                totalQuantity += (d.quantity);
            });
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            width: 200,
            dataIndex: 'partName',
            render: text => <div title={text} className={styles.partBtn}>{text}</div>
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.newPartCode',
                defaultMessage: '被替换件编号'
            }),
            dataIndex: 'newPartCode'
        }, {
            title: '',
            dataIndex: 'partId',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: (text, record) => record.price ? null : <a data-id={text} onClick={this.onRefreshPrice}>{formatMessage({
                id: 'newPanel.column.refresh',
                defaultMessage: '刷新价格'
            })}</a>
        }];

        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '订单信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.column.partOrderCode',
                                        defaultMessage: '备件订单号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateOrderCode}
                                    required>
                                        {data.id ? partSaleOrder.code : <SearchInput
                                            disabled={true}
                                            value={partSaleOrder.code}
                                            onClickSearchBtn={this.onClickSearchBtn}/>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.submitTime',
                                            defaultMessage: '提报日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(partSaleOrder.submitTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partOrderTypeName',
                                        defaultMessage: '订单类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.partOrderTypeName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.paymentType',
                                        defaultMessage: '付款方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(paymentType, partSaleOrder.paymentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.customerOrderCode',
                                        defaultMessage: '客户订单号'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.customerOrderCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPerson',
                                        defaultMessage: '收货联系人'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.receivedPerson}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.partOrderPriceTerms',
                                        defaultMessage: '价格条款'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partOrderPriceTerms, partSaleOrder.partOrderPriceTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPersonPhone',
                                        defaultMessage: '联系电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.receivedPersonPhone}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.transportType',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, partSaleOrder.transportType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.receivedPort}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, partSaleOrder.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shipmentPort',
                                        defaultMessage: '发运港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.shipmentPort}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_OPTIONS.item}>
                                        {partSaleOrder.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.receivedAddress',
                                        defaultMessage: '收货地址'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {partSaleOrder.receivedAddress}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                {partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.FCA && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.payableAccount',
                                        defaultMessage: '到付账号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="payableAccount"
                                            value={data.payableAccount}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                {(partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CIF || partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CPT ||
                                    partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CFR ||
                                partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CIP) && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.shipmentAmount',
                                        defaultMessage: '运费'
                                    })} {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            name="shipmentAmount"
                                            value={data.shipmentAmount}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>}
                                {(partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CIF || partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.CIP) && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.insuranceAmount',
                                        defaultMessage: '保费'
                                    })} {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            name="insuranceAmount"
                                            value={data.insuranceAmount}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>}
                                {
                                    (partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.FCA ||
                                        partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.FOB ||
                                        partSaleOrder.partOrderPriceTerms === partOrderPriceTerms.EXW) &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.operation.carier',
                                            defaultMessage: '指定货代'
                                        })} {...FORM_OPTIONS.item}>
                                            <TextInput
                                                name="carier"
                                                value={data.carier}
                                                onBlur={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                }
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.column.other',
                        defaultMessage: '付款信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.column.bankAccount',
                                        defaultMessage: '银行账号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateBankAccount}
                                    required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.bankAccount}
                                            onClickSearchBtn={this.onClickBankSearchBtn}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.comment',
                                        defaultMessage: '意见'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="comment"
                                            value={data.comment}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            pagination={false}
                            dataSource={details}
                            rowClassName={this.setRowClassName}
                            footer={() => <DescriptionList>
                                <Description term={formatMessage({
                                    id: 'newPanel.operation.totalAmount',
                                    defaultMessage: '总金额'
                                })}>{formatAmount(totalAmount)}
                                </Description>
                                <Description term={formatMessage({
                                    id: 'newPanel.operation.totalQuantity',
                                    defaultMessage: '总数量'
                                })}>{totalQuantity}
                                </Description>
                            </DescriptionList>}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showPartSaleOrderSelectPanel &&
                        <PartSaleOrderSelectPanel
                            selectKey={data.id}
                            isDealerUser={this.props.isDealerUser}
                            onCancel={this.onClosePartSaleOrderSelectPanel}
                            onSelect={this.onSelectPartSaleOrder} />
                    }
                    {
                        this.state.showBankSelectPanel &&
                        <BankSelectPanel
                            selectKey={data.id}
                            dealerId={partSaleOrder.dealerId}
                            onCancel={this.onCloseBankSelectPanel}
                            onSelect={this.onSelectAddedBank} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    partSaleOrderId: PropTypes.string,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, partSaleOrder) => dispatch(onSubmit(data, partSaleOrder)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
